/* $RCSFile: NumericDataType.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/DataTypes/NumericDataType.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.Web;
using System.Web.UI;

using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;

using Telerik.Web.UI;

namespace AddonNice.UI.DataTypes
{
	/// <summary>
	/// NumericDataType, parsed as a double
	/// </summary>
	public class NumericDataType : BaseDataType
	{
        public int DecimalDigits        =   2;
        public int GroupSizes           =   3;
        public string NegativePattern   =   string.Empty;
        public string PositivePattern   =   string.Empty;
        public string DecimalSeparator  =   string.Empty;
        public string GroupSeparator    =   string.Empty;

		public NumericDataType()
		{
			InnerDataType	=   PropertiesDataType.Double;
			innerValue		=   "0";
		}

		protected override void InitializeComponents()
		{
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType InitializeComponents Creating TextBox for datatype description: {0}, UseRadControl: {1}", Description,_UsesRadControl),DataTypeTraceSwitch.Sw.Info);
            if (!UseRadControl)
            {
                base.InitializeComponents();
                return;
            }
            RadNumericTextBox tx                        =   new RadNumericTextBox();
            tx.NumberFormat.DecimalDigits               =   DecimalDigits;
            tx.NumberFormat.GroupSizes                  =   GroupSizes;
            if ( !string.IsNullOrEmpty(NegativePattern))
                tx.NumberFormat.NegativePattern         =   NegativePattern;
            if ( !string.IsNullOrEmpty(PositivePattern))
                tx.NumberFormat.PositivePattern         =   PositivePattern;
            if ( !string.IsNullOrEmpty(GroupSeparator))
                tx.NumberFormat.GroupSeparator          =   GroupSeparator;
            if ( !string.IsNullOrEmpty(DecimalSeparator))
                tx.NumberFormat.DecimalSeparator        =   DecimalSeparator;
            tx.ShowSpinButtons                          =   true;
            tx.IncrementSettings.Step                   =   1;
            tx.IncrementSettings.InterceptArrowKeys     =   true;
            tx.IncrementSettings.InterceptMouseWheel    =   true;
            tx.Width                                    =   controlWidth;
            if (HandleChanges)
            {
                if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( "[V]NumericDataType InitializeComponents HandleChanges set",DataTypeTraceSwitch.Sw.Info);
                tx.AutoPostBack                         =   true;
                tx.TextChanged                          +=  new EventHandler(tx_TextChanged);
            }
            if ( ReadOnly )
                tx.Enabled                              =   false;
            innerControl                                =   tx;
            _IsInitialized                              =   true;
		}

        public override void DataBind()
        {
			try
			{
                if ( !UseRadControl)
                    base.DataBind();
                else ((RadNumericTextBox)innerControl).Text = Value2Save;
			}
			catch (Exception ex)
			{
                if ( DataTypeTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]NumericDataType DataBind ex: {0}",ex),DataTypeTraceSwitch.Sw.Info);
                throw;
			}
        }

        /// <summary>
        /// Update value from control: used by eventhandler after a control change event triggered
        /// </summary>
        public override  string ReadDataFromEditControl()
		{
            if ( !UseRadControl)
                return base.ReadDataFromEditControl();
            Control Ctl =   EditControl;
            if (DataTypeTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType ReadDataFromEditControl BEG Control is null: {0}, Val: {1}.", (Ctl == null), Val ), DataTypeTraceSwitch.Sw.Info);
            if ( Ctl ==   null )
                return Val;
            if ( Ctl is RadNumericTextBox)
            {
                RadNumericTextBox Tx    =   (RadNumericTextBox)Ctl;
                innerValue              =   Tx.Text;
                if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl UseRadControl Set Value: {0}", innerValue),DataTypeTraceSwitch.Sw.Info);
            }
            if (DataTypeTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType ReadDataFromEditControl END InnerValue: {0}.", innerValue), DataTypeTraceSwitch.Sw.Info);
            return Val;
        }
        
      /// <summary>
        /// Assume it own range validator
        /// </summary>
        public override bool SelfRangeValidator
        {
			get{return true;}
		}

        public override void SetMinValue(double minVal)
        {
            if ( !UseRadControl)
                return;
            if ( innerControl == null )
                return;
            ((RadNumericTextBox)innerControl).MinValue  =   minVal;
        }

        public override void SetMaxValue(double maxVal)
        {
            if ( !UseRadControl)
                return;
            if ( innerControl == null )
                return;
            ((RadNumericTextBox)innerControl).MaxValue  =   maxVal;
        }

        public override Control EditControl
		{
			get
			{
                if ( !UseRadControl)
                    return base.EditControl;
                bool iCtrlDefined   =    ( innerControl != null );
				if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl GET iCtrlDefined : {0}", iCtrlDefined ),DataTypeTraceSwitch.Sw.Info);
				if ( !iCtrlDefined )
					InitializeComponents();
				if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl Get Value2Save: {0}", Value2Save),DataTypeTraceSwitch.Sw.Info);
				return innerControl;
			}
			set
			{
                if (!UseRadControl)
                {
                    base.EditControl                =   value;
                    return;
                }
                bool iCtrlDefined                   =    ( innerControl != null );
				if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl SET iCtrlDefined : {0}", iCtrlDefined ),DataTypeTraceSwitch.Sw.Info);
                bool iCtrlDefinedEqual              =   ( iCtrlDefined && innerControl.Equals(value) );
			    if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl SET innerControl equal to value : {0}", iCtrlDefinedEqual ),DataTypeTraceSwitch.Sw.Info);
                if (value is RadNumericTextBox)
                {
                    if (!iCtrlDefinedEqual)
                    {
                        innerControl                =   value;
                        if (HandleChanges)
                        {
                            RadNumericTextBox Tx    =   (RadNumericTextBox)value;
                            Tx.AutoPostBack         =   true;
                            Tx.TextChanged          +=  new EventHandler(tx_TextChanged);
                        }
                    }
                    //Update value from control
                    // DO NOT use Value but use InnerValue
                    innerValue = ((RadNumericTextBox)innerControl).Text;
                    if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NumericDataType EditControl UseRadControl Set Value: {0}", innerValue),DataTypeTraceSwitch.Sw.Info);
                    return;
                }
				string msg  =   string.Format("[E]NumericDataType Set UseRadControl EditControl: {0}, not RadNumericTextBox",value.GetType());
				if ( DataTypeTraceSwitch.Sw.TraceError )
                    Trace.WriteLine(msg,DataTypeTraceSwitch.Sw.Info);
				throw new ArgumentException(msg);
			}
		}

        public override string Val
		{
			get
			{
				return innerValue;
			}
			set
			{
				try
				{
					innerValue = double.Parse(value,CultureInfo.InvariantCulture).ToString();
				}
				catch (Exception ex)
				{
					if ( DataTypeTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"NumericDataType Set Value: {0}, ex: {1}",value,ex),DataTypeTraceSwitch.Sw.Info);
				}
			}
		}

		public override string Description
		{
			get
			{
				return "Numeric";
			}
		}
	}
}